package service

import (
	"errors"
	"exam_go/model"
	"fmt"
	"time"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type UserService struct {
}

type Userinforesp struct {
	UserID  int64  `json:"userId"`
	Number  string `json:"number"`
	Name    string `json:"name"`
	IsAdmin bool   `json:"isAdmin"`
}

type SearchGoodsResponse struct {
	Total int64       `json:"total"`
	List  []GoodsList `json:"list"` // 商品列表
}

type GoodsList struct {
	ID       int64   `json:"Id"`
	Type     string  `json:"type"`     // 商品类型
	Img      string  `json:"img"`      // 商品图片
	Price    float64 `json:"price"`    // 商品价格
	Name     string  `json:"name"`     // 商品名称
	Describe string  `json:"describe"` // 商品描述
}

type Ordergoodres struct {
	ID   int    `json:"titleid,omitempty"`
	Type string `json:"type,omitempty"`
}

type GoodInfores struct { // 用户看到的商品信息
	ID       int     `json:"id"`
	Name     string  `json:"name"`
	Price    float64 `json:"price"`
	Img      string  `json:"img"`
	Describe string  `json:"describe"`
}

type Buyres struct {
	ID     int64 `json:"id"`
	GoodID int64 `json:"goodid"`
	Number int   `json:"number"`
}

type Commentres struct {
	OrderID int64 `json:"orderid"`
	UserID  int64 `json:"userid"`
}
type getOrderres struct {
	List []OrdersList `json:"list"`
}

type OrdersList struct {
	OrderID     int64     `json:"orderid"`
	GoodID      int64     `json:"goodid"`
	OrderName   string    `json:"ordername"`
	Number      int       `json:"number"`
	OrderStatus int       `json:"orderstatus"`
	OrderAmount float64   `json:"orderamount"`
	CreatedAt   time.Time `json:"createat"`
}

type Userinfores struct {
	ID        int64     `json:"id"`
	Number    string    `json:"number"`
	Name      string    `json:"name"`
	IsVIP     bool      `json:"isvip"`
	CreatedAt time.Time `json:"createat"`
}

type ServiceTimeres struct {
	List []ServiceTimes `json:"list"`
}

type ServiceTimes struct {
	ID        int64     `json:"id"`
	ServiceID int64     `json:"service_id"`
	Date      time.Time `json:"date"`
	Time      time.Time `json:"time"`
	Available bool      `json:"available"`
}

func (u UserService) HandleSignupservice(c *gin.Context) (resp *Userinforesp, err error) {
	var form struct {
		Number   string `form:"number" json:"number" binding:"required"`
		Name     string `json:"name" form:"name" binding:"required"`
		Password string `json:"password" form:"password" binding:"required"`
	}
	if err := c.ShouldBind(&form); err != nil {
		return nil, err
	}
	user := &model.User{}
	if err := model.DB.Where("number = ?", form.Number).First(&user).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		user = &model.User{
			Number:   form.Number,
			Name:     form.Name,
			Password: form.Password,
			IsAdmin:  false,
			Status:   1,
		}
		if err := model.DB.Create(&user).Error; err != nil {
			return nil, err
		}
		session := sessions.Default(c)
		session.Set("userId", user.ID)
		session.Set("status", 1)
		if err := session.Save(); err != nil {
			return nil, err
		}
		return &Userinforesp{
			UserID: user.ID,
			Number: user.Number,
			Name:   user.Name,
		}, nil
	}
	return nil, errors.New("已存在相同的账号")
}

func (u UserService) HandleLoginService(c *gin.Context) (resp *Userinforesp, err error) {
	var form struct {
		Number   string `form:"number" json:"number" binding:"required"`
		Password string `json:"password" form:"password" binding:"required"`
	}
	if err := c.ShouldBind(&form); err != nil {
		return nil, err
	}
	user := &model.User{}
	if err := model.DB.Where("number = ?", form.Number).First(&user).Error; err != nil {
		return nil, err
	}
	if form.Password != user.Password {
		return nil, errors.New("密码不正确")
	}
	if user.Status == 0 {
		return nil, errors.New("您的账户已被禁用")
	}
	session := sessions.Default(c)
	session.Set("userId", user.ID)
	session.Set("isAdmin", user.IsAdmin)
	if err := session.Save(); err != nil {
		return nil, err
	}
	fmt.Println(session.Get("userId"))
	return &Userinforesp{
		UserID:  user.ID,
		Name:    user.Name,
		Number:  user.Number,
		IsAdmin: user.IsAdmin,
	}, nil
}

func (u UserService) HandleGetGoodListsService(c *gin.Context) (resp *SearchGoodsResponse, err error) {
	var uri struct {
		Type  string `form:"type" json:"type" uri:"type"`
		Page  int    `form:"page" json:"page" uri:"page" validate:"gte=1"`
		Limit int    `form:"limit" json:"limit" uri:"limit"`
		Name  string `form:"name" json:"name" uri:"name"` // 新增 name 参数，支持模糊查询
	}

	// 绑定 URI 参数
	if err := c.ShouldBindQuery(&uri); err != nil {
		return nil, err
	}

	// 定义响应结构体
	resp = &SearchGoodsResponse{}
	var goodList []GoodsList
	var total int64

	// 构建查询
	var items []GoodsList
	var services []GoodsList

	// 查询条件
	condition := "isOnShelf = ?"
	var args []interface{}
	args = append(args, true)

	// 如果传递了 name 参数，则进行模糊查询
	if uri.Name != "" {
		condition += " AND name LIKE ?"
		args = append(args, "%"+uri.Name+"%")
	}

	if uri.Type == "" {
		// 无 type 参数，分别查询 items 和 services 表
		// 查询 items 表
		if err := model.DB.Model(&model.Item{}).
			Select("id, 'item' AS type, price, name, img, `describe`").
			Where(condition, args...).Scan(&items).Error; err != nil {
			return nil, err
		}

		// 查询 services 表
		if err := model.DB.Model(&model.Service{}).
			Select("id, 'service' AS type, price, name, img, `describe`").
			Where(condition, args...).Scan(&services).Error; err != nil {
			return nil, err
		}

		// 合并结果
		goodList = append(items, services...)
		total = int64(len(goodList)) // 统计总数

	} else {
		// 有 type 参数，根据 type 查询特定表
		var subQuery *gorm.DB
		if uri.Type == "item" {
			subQuery = model.DB.Model(&model.Item{}).
				Select("id, 'item' AS type, price, name, img, `describe`").
				Where(condition, args...)
		} else if uri.Type == "service" {
			subQuery = model.DB.Model(&model.Service{}).
				Select("id, 'service' AS type, price, name, img, `describe`").
				Where(condition, args...)
		}

		// 查询并统计记录
		if err := subQuery.Scan(&goodList).Error; err != nil {
			return nil, err
		}
		total = int64(len(goodList))
	}

	// 构建响应数据
	resp = &SearchGoodsResponse{
		List:  goodList,
		Total: total,
	}

	return resp, nil
}

func (u UserService) HandleAddCartService(c *gin.Context) (resp *Ordergoodres, err error) {
	var uri struct {
		ID     int64 `form:"id" json:"id" binding:"required"`
		Number int   `form:"number" json:"number" binding:"required"`
	}
	session := sessions.Default(c)
	if err := c.ShouldBind(&uri); err != nil {
		return nil, err
	}
	ordergood := &Ordergoodres{}
	good := &model.Good{}
	if err := model.DB.Where("id = ?", uri.ID).First(&good).Error; err != nil {
		return nil, err
	}
	var query *gorm.DB
	itemQuery := model.DB.Model(&model.Item{}).Select("id").Where("isOnShelf = ?", true)
	serviceQuery := model.DB.Model(&model.Service{}).Select("id").Where("isOnShelf = ?", true)
	query = model.DB.Model(&model.Good{}).Where("id IN (?) OR id IN (?)", itemQuery, serviceQuery).Where("id = ?", uri.ID)
	fmt.Println(session.Get("userId"))
	fmt.Println(query.First(&ordergood))

	order := &model.Cart{
		UserID: session.Get("userId").(int64),
		GoodID: uri.ID,
		Number: uri.Number,
	}
	if err := model.DB.Create(order).Error; err != nil {
		return nil, err
	} else {
		fmt.Println("Order created successfully")
	}

	return ordergood, nil
}

type OrderGoodResponse struct {
	OrderID   int64        `json:"order_id"`   // 新创建订单的 ID
	OrderGood Ordergoodres `json:"order_good"` // 原来的 ordergood 信息
}

func (u UserService) HandleOrderGoodService(c *gin.Context) (resp *OrderGoodResponse, err error) {
	var uri struct {
		ID     int64 `form:"id" json:"id" binding:"required"`
		Number int   `form:"number" json:"number" binding:"required"`
	}
	session := sessions.Default(c)
	if err := c.ShouldBind(&uri); err != nil {
		return nil, err
	}

	ordergood := &Ordergoodres{}
	good := &model.Good{}
	if err := model.DB.Where("id = ?", uri.ID).First(&good).Error; err != nil {
		return nil, err
	}

	var query *gorm.DB
	itemQuery := model.DB.Model(&model.Item{}).Select("id").Where("isOnShelf = ?", true)
	serviceQuery := model.DB.Model(&model.Service{}).Select("id").Where("isOnShelf = ?", true)
	query = model.DB.Model(&model.Good{}).Where("id IN (?) OR id IN (?)", itemQuery, serviceQuery).Where("id = ?", uri.ID)
	if err := query.First(&ordergood).Error; err != nil {
		return nil, err
	}

	order := &model.Order{
		UserID: session.Get("userId").(int64),
		GoodID: uri.ID,
		Number: uri.Number,
		Status: 0,
	}
	if err := model.DB.Create(order).Error; err != nil {
		// 处理插入失败的错误
		fmt.Printf("Failed to create order: %v\n", err)
		return nil, err
	} else {
		fmt.Println("Order created successfully")
	}

	// 返回创建的订单信息以及 ordergood 的完整信息
	return &OrderGoodResponse{
		OrderID:   order.ID,
		OrderGood: *ordergood,
	}, nil
}

func (u UserService) HandleGetGoodInfoService(c *gin.Context) (resp *GoodInfores, err error) {
	var uri struct {
		ID int64 `form:"id" json:"id" binding:"required"`
	}
	if err := c.ShouldBind(&uri); err != nil {
		return nil, err
	}
	var goodInfo *GoodInfores
	good := &model.Good{}
	if err := model.DB.Where("id = ?", uri.ID).First(&good).Error; err != nil {
		return nil, err
	}

	if good.Type == "item" {
		item := &model.Item{}
		query := model.DB.Where("id = ?", uri.ID).First(item)
		if query.Error != nil {
			fmt.Printf("Failed to fetch item: %v", query.Error)
			return
		}
		// 将 Item 的字段赋值到 GoodInfores
		goodInfo = &GoodInfores{
			ID:       int(item.ID),
			Name:     item.Name,
			Price:    item.Price,
			Img:      item.Img,
			Describe: item.Describe,
		}
	} else {
		service := &model.Service{}
		query := model.DB.Where("id = ?", uri.ID).First(service)
		if query.Error != nil {
			fmt.Printf("Failed to fetch service: %v", query.Error)
			return
		}
		// 将 Service 的字段赋值到 GoodInfores
		goodInfo = &GoodInfores{
			ID:       int(service.ID),
			Name:     service.Name,
			Price:    service.Price,
			Img:      service.Img,
			Describe: service.Describe,
		}
	}

	return goodInfo, nil
}

func (u UserService) HandleBuyService(c *gin.Context) (resp *Buyres, err error) {
	var uri struct {
		ID int64 `form:"id" json:"id" binding:"required"`
	}

	session := sessions.Default(c)
	if err := c.ShouldBind(&uri); err != nil {
		return nil, err
	}

	// 获取当前会话的 user_id
	sessionUserID := session.Get("userId").(int64)

	// 查询 Order 表中与 uri.ID 相匹配的记录
	var order model.Order
	if err := model.DB.Where("id = ?", uri.ID).First(&order).Error; err != nil {
		return nil, err
	}

	// 检查 Order 的 user_id 是否与会话中的 user_id 相同
	if order.UserID != sessionUserID {
		return nil, errors.New("unauthorized access to this order")
	}

	// 如果订单已支付，直接返回错误
	if order.Status != 0 {
		return nil, errors.New("order has already been paid")
	}

	// 根据 good_id 查询对应的商品信息
	var good model.Good
	if err := model.DB.Where("id = ?", order.GoodID).First(&good).Error; err != nil {
		return nil, err
	}

	// 如果 good 属于 items 表，检查库存 rest
	if good.Type == "item" {
		var item model.Item
		if err := model.DB.Where("id = ?", order.GoodID).First(&item).Error; err != nil {
			return nil, err
		}

		// 检查库存数量是否足够
		if order.Number > item.Rest {
			return nil, errors.New("insufficient stock to complete purchase")
		}

		// 更新 rest 数量
		if err := model.DB.Model(&model.Item{}).Where("id = ?", order.GoodID).Update("rest", item.Rest-order.Number).Error; err != nil {
			return nil, err
		}
	} else if good.Type == "service" { // 如果是服务类型，检查 `service_times` 表
		var serviceTime model.ServiceTime
		if err := model.DB.Where("service_id = ? AND order_id = ? AND user_id = ?", order.GoodID, order.ID, sessionUserID).First(&serviceTime).Error; err != nil {
			return nil, errors.New("service not available or unauthorized access to this service")
		}
	}

	order.Status = 1
	if err := model.DB.Save(&order).Error; err != nil {
		return nil, err
	}

	// 返回购买信息
	buyres := Buyres{
		ID:     order.ID,
		GoodID: order.GoodID,
		Number: order.Number,
	}

	return &buyres, nil
}

func (u UserService) HandleCommentService(c *gin.Context) (resp *Commentres, err error) {
	var uri struct {
		ID      int64  `json:"id" binding:"required"`
		Comment string `json:"comment" binding:"required"`
	}

	if err := c.ShouldBind(&uri); err != nil {
		return nil, err
	}

	fmt.Println(uri.ID)

	// 检查 `orders` 表中是否存在指定的 `ID`
	var order model.Order
	if err := model.DB.Where("id = ?", uri.ID).First(&order).Error; err != nil {
		return nil, err
	}
	if order.Status != 1 {
		return nil, errors.New("order is not paid")
	}

	session := sessions.Default(c)
	// 获取当前会话的 `user_id`
	sessionUserID := session.Get("userId").(int64)

	// 获取 `good_id`
	goodID := order.GoodID

	// 查询 `goods` 表，获取 `type`
	var good model.Good
	if err := model.DB.Where("id = ?", goodID).First(&good).Error; err != nil {
		return nil, err
	}

	// 获取 `type` 字段的值
	goodType := good.Type

	// 在 `comments` 表中创建一条记录
	comment := model.Comment{
		Type:    goodType,
		OrderID: int64(uri.ID),
		UserID:  sessionUserID,
		Comment: uri.Comment,
	}
	if err := model.DB.Create(&comment).Error; err != nil { // 如果创建记录失败，返回错误
		return nil, err
	}
	commentres := Commentres{
		OrderID: int64(uri.ID),
		UserID:  sessionUserID,
	}

	return &commentres, nil
}

func (u UserService) HandleDeleteOrderService(c *gin.Context) (err error) {
	var uri struct {
		ID int64 `form:"id" json:"id" binding:"required"`
	}
	if err := c.ShouldBindQuery(&uri); err != nil {
		return err
	}

	session := sessions.Default(c)
	sessionUserID := session.Get("userId").(int64)

	var order model.Order
	if err := model.DB.Where("id = ?", uri.ID).First(&order).Error; err != nil {
		return err
	}
	if order.UserID != sessionUserID {
		return errors.New("unauthorized: user_id does not match")
	}
	if order.Status != 0 {
		return errors.New("unauthorized: order is paid")
	}

	// 删除记录
	if err := model.DB.Delete(&order).Error; err != nil {
		return err
	}
	return nil
}

func (u UserService) HandleGetOrderInfoService(c *gin.Context) (resp *getOrderres, err error) {
	// 定义参数结构体
	var uri struct {
		OrderName   string `form:"ordername" json:"ordername"`
		OrderID     int64  `form:"orderid" json:"orderid"`
		OrderStatus int    `form:"orderstatus" json:"orderstatus"`
	}

	// 绑定请求参数
	if err := c.ShouldBind(&uri); err != nil {
		return nil, err
	}

	// 获取当前用户的 userId
	session := sessions.Default(c)
	userId := session.Get("userId").(int64)

	// 初始化返回结构体
	resp = &getOrderres{}
	var orders []model.Order // 假设 orders 表在数据库中的模型是 model.Order

	// 构造查询
	query := model.DB.Model(&model.Order{}).Where("user_id = ?", userId) // 添加 user_id 条件
	if uri.OrderName != "" {
		// 查询 good_id 对应的 items 或 services 表中的 name
		itemQuery := model.DB.Model(&model.Item{}).Select("id").Where("name LIKE ?", "%"+uri.OrderName+"%")
		serviceQuery := model.DB.Model(&model.Service{}).Select("id").Where("name LIKE ?", "%"+uri.OrderName+"%")
		query = query.Where("good_id IN (?) OR good_id IN (?)", itemQuery, serviceQuery)
	}
	if uri.OrderID != 0 {
		query = query.Where("id = ?", uri.OrderID) // 查询 orders 表自身的 ID
	}
	if uri.OrderStatus != 0 {
		query = query.Where("status = ?", uri.OrderStatus)
	}

	// 查询 orders 表
	if err := query.Find(&orders).Error; err != nil {
		return nil, fmt.Errorf("failed to query orders: %v", err)
	}

	// 遍历查询结果并补充返回值
	for _, order := range orders {
		var orderName string
		var orderAmount float64

		// 根据 good_id 获取 name 和 price
		item := &model.Item{}
		service := &model.Service{}
		itemErr := model.DB.Where("id = ?", order.GoodID).First(&item).Error
		serviceErr := model.DB.Where("id = ?", order.GoodID).First(&service).Error

		if itemErr == nil {
			orderName = item.Name
			orderAmount = item.Price * float64(order.Number)
		} else if serviceErr == nil {
			orderName = service.Name
			orderAmount = service.Price * float64(order.Number)
		} else {
			// 未找到 good_id 对应记录，跳过此订单
			continue
		}

		// 构造单条记录
		resp.List = append(resp.List, OrdersList{
			OrderID:     order.ID, // 这里是 orders 表的 ID
			GoodID:      order.GoodID,
			OrderName:   orderName,
			Number:      order.Number,
			OrderStatus: order.Status,
			OrderAmount: orderAmount,
			CreatedAt:   order.CreatedAt,
		})
	}

	return resp, nil
}

func (u UserService) HandleGetCartInfoService(c *gin.Context) (resp *getOrderres, err error) {
	// 获取当前用户的 userId
	session := sessions.Default(c)
	userID := session.Get("userId").(int64)

	// 获取前端传递的参数
	var uri struct {
		Name string `form:"name" json:"name"` // 商品名称，用于模糊搜索
		Type string `form:"type" json:"type"` // 商品类型，用于筛选 'item' 或 'service'
	}

	// 绑定查询参数
	if err := c.ShouldBindQuery(&uri); err != nil {
		return nil, err
	}

	// 查询 carts 表中 user_id 与当前用户 id 匹配的所有记录
	var cart []model.Cart
	// 构建查询条件
	query := model.DB.Where("user_id = ?", userID)

	// 如果传递了 type 参数，添加筛选条件
	if uri.Type != "" {
		// 根据 type 值选择查询 items 表或 services 表
		if uri.Type == "item" {
			// 使用 item 表的商品 id 进行查询
			query = query.Where("good_id IN (?)", model.DB.Model(&model.Item{}).Select("id"))
		} else if uri.Type == "service" {
			// 使用 service 表的商品 id 进行查询
			query = query.Where("good_id IN (?)", model.DB.Model(&model.Service{}).Select("id"))
		}
	}

	// 如果传递了 name 参数，进行模糊搜索
	if uri.Name != "" {
		// 根据 type 判断是查询 items 表还是 services 表的 name 字段
		if uri.Type == "item" || uri.Type == "" {
			// name 模糊搜索 items 表中的商品
			query = query.Where("good_id IN (?)", model.DB.Model(&model.Item{}).Select("id").Where("name LIKE ?", "%"+uri.Name+"%"))
		}
		if uri.Type == "service" || uri.Type == "" {
			// name 模糊搜索 services 表中的商品
			query = query.Or("good_id IN (?)", model.DB.Model(&model.Service{}).Select("id").Where("name LIKE ?", "%"+uri.Name+"%"))
		}
	}

	// 执行查询
	if err := query.Find(&cart).Error; err != nil {
		return nil, err
	}

	// 准备返回结果的列表
	var orderList = &getOrderres{}

	// 遍历购物车记录，获取详细信息
	for _, cartt := range cart {
		// 获取商品信息
		var good model.Good
		if err := model.DB.Where("id = ?", cartt.GoodID).First(&good).Error; err != nil {
			return nil, err
		}

		// 根据 type 查询对应表（items 或 services），并获取价格和名称
		var price float64
		var orderName string
		if good.Type == "item" {
			var item model.Item
			if err := model.DB.Where("id = ?", cartt.GoodID).First(&item).Error; err != nil {
				return nil, err
			}
			price = item.Price
			orderName = item.Name // 获取 item 名称
		} else if good.Type == "service" {
			var service model.Service
			if err := model.DB.Where("id = ?", cartt.GoodID).First(&service).Error; err != nil {
				return nil, err
			}
			price = service.Price
			orderName = service.Name // 获取 service 名称
		}

		// 计算总价
		total := price * float64(cartt.Number)

		// 将订单信息添加到结果中，并传出 OrderName
		orderList.List = append(orderList.List, OrdersList{
			OrderID:     cartt.ID,
			GoodID:      cartt.GoodID,
			Number:      cartt.Number,
			OrderAmount: total,
			CreatedAt:   cartt.CreatedAt,
			OrderName:   orderName, // 将商品名称传给 OrderName
		})
	}

	// 返回结果结构体
	return orderList, nil
}
func (u UserService) HandleGetUserInfoService(c *gin.Context) (resp *Userinfores, err error) {
	// 从 session 中获取 user_id
	session := sessions.Default(c)
	sessionUserID := session.Get("userId").(int64)

	// 查询 `users` 表中与 sessionUserID 匹配的用户信息
	var user model.User
	if err := model.DB.Where("id = ?", sessionUserID).First(&user).Error; err != nil {
		return nil, err
	}

	// 构建返回的用户信息
	userinfo := Userinfores{
		ID:        user.ID,
		Number:    user.Number,
		Name:      user.Name,
		IsVIP:     user.IsVIP,
		CreatedAt: user.CreatedAt,
	}

	return &userinfo, nil
}

func (u UserService) HandleGetServiceTimesService(c *gin.Context) (resp *ServiceTimeres, err error) {
	var uri struct {
		ID int64 `form:"id" json:"id" binding:"required"`
	}

	// 绑定查询参数
	if err := c.ShouldBindQuery(&uri); err != nil {
		return nil, err
	}

	// 创建一个空的 ServiceTimeres 实例
	var serviceTimes = &ServiceTimeres{}

	// 查询 service_times 表中与传入 service_id 匹配的所有记录
	if err := model.DB.Where("service_id = ?", uri.ID).Find(&serviceTimes.List).Error; err != nil {
		return nil, err
	}

	// 返回查询结果
	return serviceTimes, nil
}

type OrderServiceres struct {
	OrderID   int64     `json:"order_id"`
	ServiceID int64     `json:"service_id"`
	UserID    int64     `json:"user_id"`
	Date      time.Time `json:"date"`
	Time      time.Time `json:"time"`
}

func (u UserService) HandleOrderServiceService(c *gin.Context) (resp *OrderServiceres, err error) {
	var uri struct {
		ID int64 `form:"id" json:"id" binding:"required"`
	}

	// 绑定查询参数
	if err := c.ShouldBindQuery(&uri); err != nil {
		return nil, err
	}

	// 查询 service_times 表中与传入 ID 匹配的记录
	var serviceTime model.ServiceTime
	if err := model.DB.Where("id = ?", uri.ID).First(&serviceTime).Error; err != nil {
		return nil, err
	}

	// 检查 service_time 是否可用
	if !serviceTime.Available {
		return nil, errors.New("service time is not available")
	}

	// 获取当前会话的 user_id
	session := sessions.Default(c)
	sessionUserID := session.Get("userId").(int64)

	// 创建 orders 表的新记录
	newOrder := model.Order{
		UserID: sessionUserID,
		GoodID: serviceTime.ServiceID, // 使用 service_id 作为 good_id
		Number: 1,                     // 假设每个服务订单是 1 个单位
		Status: 0,                     // 初始时未支付
	}
	if err := model.DB.Create(&newOrder).Error; err != nil {
		return nil, err
	}

	// 更新 service_times 表的记录
	if err := model.DB.Model(&serviceTime).Updates(map[string]interface{}{
		"user_id":   sessionUserID,
		"order_id":  newOrder.ID,
		"available": false,
	}).Error; err != nil {
		return nil, err
	}

	// 构造返回的结果
	orderServiceres := OrderServiceres{
		OrderID:   newOrder.ID,
		ServiceID: serviceTime.ServiceID,
		UserID:    sessionUserID,
		Date:      serviceTime.Date,
		Time:      serviceTime.Time,
	}

	return &orderServiceres, nil
}

type SoldDataRes struct {
	List []SoldType `json:"list"`
}

type SoldType struct {
	Type   string `json:"type"`
	Number int    `json:"number"`
}

func (u UserService) HandleGetSoldQuantityService(c *gin.Context) (resp *SoldDataRes, err error) {
	// 创建返回数据结构
	resp = &SoldDataRes{
		List: []SoldType{
			{
				Type:   "物品",
				Number: 0,
			},
			{
				Type:   "服务",
				Number: 0,
			},
		},
	}

	// 查询 orders 表，status 为 2 或 3 的记录
	var orders []model.Order
	if err := model.DB.Where("status IN (?)", []int{2, 3}).Find(&orders).Error; err != nil {
		return nil, err
	}

	// 分类计算数量
	for _, order := range orders {
		var good model.Good
		// 根据 good_id 查询对应商品信息
		if err := model.DB.Where("id = ?", order.GoodID).First(&good).Error; err != nil {
			return nil, err
		}

		// 如果是 item 类型商品，累加数量
		if good.Type == "item" {
			var item model.Item
			if err := model.DB.Where("id = ?", order.GoodID).First(&item).Error; err != nil {
				return nil, err
			}
			resp.List[0].Number += order.Number
		}

		// 如果是 service 类型商品，累加数量
		if good.Type == "service" {
			var service model.Service
			if err := model.DB.Where("id = ?", order.GoodID).First(&service).Error; err != nil {
				return nil, err
			}
			resp.List[1].Number += order.Number
		}
	}

	return resp, nil
}

type EditSelfInfores struct {
	Username string `json:"username"`
	Number   string `json:"number"`
}

func (u UserService) HandleEditSelfInfoService(c *gin.Context) (resp *EditSelfInfores, err error) {
	// 获取 session 中的 userId
	session := sessions.Default(c)
	userID := session.Get("userId").(int64)
	fmt.Println(userID)

	// 定义要更新的字段
	var uri struct {
		Username string `json:"username" binding:"required"` // 前端传参时使用 username
		Number   string `json:"number" binding:"required"`   // 前端传参时使用 number
	}

	// 绑定前端传来的数据
	if err := c.ShouldBind(&uri); err != nil {
		return nil, err
	}

	// 打印传入的参数（可选，用于调试）
	fmt.Println(uri.Username)
	fmt.Println(uri.Number)

	// 根据 user_id 查询用户信息
	var user model.User
	if err := model.DB.Where("id = ?", userID).First(&user).Error; err != nil {
		return nil, err // 查询失败，返回错误
	}

	// 更新用户信息
	user.Name = uri.Username
	user.Number = uri.Number

	// 保存更新后的用户信息
	if err := model.DB.Save(&user).Error; err != nil {
		return nil, err // 保存失败，返回错误
	}

	// 返回更新后的用户信息
	resp = &EditSelfInfores{
		Username: user.Name,
		Number:   user.Number,
	}

	return resp, nil
}

type DeleteCartres struct {
	CartId int64 `json:"cart_id"`
}

func (u UserService) HandleDeleteCartService(c *gin.Context) (resp *DeleteCartres, err error) {
	// 获取请求参数中的 cart_id
	var form struct {
		ID int64 `json:"id" form:"id" binding:"required"`
	}

	// 绑定参数
	if err := c.ShouldBindQuery(&form); err != nil {
		return nil, err
	}

	// 获取 session 中的 user_id
	session := sessions.Default(c)
	sessionUserID := session.Get("userId").(int64)

	// 根据 cart_id 和 user_id 查找要删除的记录
	var cart model.Cart
	if err := model.DB.Where("id = ? AND user_id = ?", form.ID, sessionUserID).First(&cart).Error; err != nil {
		return nil, fmt.Errorf("未找到对应的购物车记录: %v", err)
	}

	// 删除记录
	if err := model.DB.Delete(&cart).Error; err != nil {
		return nil, fmt.Errorf("删除购物车记录失败: %v", err)
	}

	// 返回响应
	resp = &DeleteCartres{
		CartId: form.ID,
	}
	return resp, nil
}

func (u UserService) HandleRefundService(c *gin.Context) (err error) {
	// 获取请求参数中的 order_id
	var form struct {
		Orderid int64 `json:"orderid" form:"orderid" binding:"required"`
	}

	// 绑定请求参数
	if err := c.ShouldBind(&form); err != nil {
		return fmt.Errorf("invalid request parameters: %v", err) // 如果参数绑定失败，返回错误
	}

	// 获取当前用户的 user_id
	session := sessions.Default(c)
	userID := session.Get("userId").(int64)

	// 查询 orders 表，找出符合条件的订单
	var order model.Order
	if err := model.DB.Where("id = ? AND user_id = ?", form.Orderid, userID).First(&order).Error; err != nil {
		return fmt.Errorf("未找到订单") // 如果没有找到订单，返回错误
	}

	// 检查订单状态
	if order.Status != 1 {
		return fmt.Errorf("订单状态错误") // 当状态不为 1 时，返回错误
	}

	// 将订单状态改为 2（退款中）
	order.Status = 2
	if err := model.DB.Save(&order).Error; err != nil {
		return fmt.Errorf("failed to update order status: %v", err) // 如果更新失败，返回错误
	}

	// 返回成功
	return nil
}

func (u UserService) HandleUserCommentService(c *gin.Context) (err error) {
	// 获取请求参数中的 order_id 和 comment
	var form struct {
		Orderid int64  `json:"orderid" form:"orderid" binding:"required"`
		Comment string `json:"comment" form:"comment" binding:"required"`
	}

	// 绑定请求参数
	if err = c.ShouldBind(&form); err != nil {
		return err
	}

	// 获取 session 中的 user_id
	session := sessions.Default(c)
	userID := session.Get("userId").(int64)

	// 查询 orders 表，验证该订单是否属于当前用户
	var order model.Order
	if err := model.DB.Where("id = ? AND user_id = ?", form.Orderid, userID).First(&order).Error; err != nil {
		// 如果没有找到订单，说明订单不属于当前用户，返回错误
		return fmt.Errorf("order not found or does not belong to the current user")
	}

	// 在 comments 表中插入新评论
	comment := &model.Comment{
		OrderID: form.Orderid,
		UserID:  userID,
		Comment: form.Comment,
	}

	if err := model.DB.Create(comment).Error; err != nil {
		return err
	}

	// 返回成功
	return nil
}

func (u UserService) HandleEditPasswdService(c *gin.Context) (err error) {
	// 获取请求参数中的 NewPasswd 和 CurrentPasswd
	var form struct {
		NewPasswd     string `json:"NewPasswd" form:"new_passwd" binding:"required"`
		CurrentPasswd string `json:"CurrentPasswd" form:"current_passwd" binding:"required"`
	}

	// 绑定请求参数
	if err := c.ShouldBind(&form); err != nil {
		return err // 参数绑定失败
	}

	// 获取当前用户的 user_id
	session := sessions.Default(c)
	userID := session.Get("userId").(int64)

	// 查询 users 表，确认当前密码是否匹配
	var user model.User
	if err := model.DB.Where("id = ?", userID).First(&user).Error; err != nil {
		return fmt.Errorf("user not found")
	}

	if user.Password != form.CurrentPasswd {
		return fmt.Errorf("current password is incorrect")
	}

	// 更新密码为新密码
	user.Password = form.NewPasswd
	if err := model.DB.Save(&user).Error; err != nil {
		return fmt.Errorf("failed to update password: %v", err)
	}

	// 返回 nil 表示操作成功
	return nil
}

type GetRestres struct {
	Rest int `json:"rest"`
}

func (u UserService) HandleGetRestService(c *gin.Context) (resp *GetRestres, err error) {
	// 获取请求参数中的 id
	var form struct {
		ID int64 `json:"id" form:"id" binding:"required"`
	}

	// 绑定请求参数
	if err := c.ShouldBind(&form); err != nil {
		return nil, err // 参数绑定失败
	}

	// 查询 items 表中 id 对应的记录
	var item model.Item
	if err := model.DB.Where("id = ?", form.ID).First(&item).Error; err != nil {
		return nil, fmt.Errorf("item not found with id %d", form.ID)
	}

	// 返回 rest 字段值
	resp = &GetRestres{
		Rest: item.Rest,
	}

	return resp, nil
}
